package vn.edu.saigontech.ncms.web;

import java.io.IOException;

import flexjson.JSONSerializer;
import vn.edu.saigontech.ncms.model.enumeration.Result;

@SuppressWarnings("serial")
public abstract class AbstractValidator extends BaseAction {

	public String execute() {
		try {
			return this.check();
		} catch (Exception ex) {
		}
		return this.toFailure();
	}

	public abstract String check();

	public String toSuccess() {
		try {
			RESPONSE().getOutputStream().println(
					new JSONSerializer().serialize(new ErrorMessage(
							Result.SUCCESS, this.message)));
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return NONE;
	}

	public String toFailure() {
		try {
			RESPONSE().getOutputStream().println(
					new JSONSerializer().serialize(new ErrorMessage(
							Result.FAILURE, this.message)));
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return NONE;
	}

	public void sendError(String message) {
		this.setMessage(message);
		throw new ValidationException();
	}

	public void sendValueError(String key, Object... params) {
		this.setValueMessage(key, params);
		throw new ValidationException();
	}

	public void sendKeyError(String key, String... paramKeys) {
		this.setKeyMessage(key, paramKeys);
		throw new ValidationException();
	}
}